package com.example.bgzk;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class UdpClient{
    public  String  SERVER_IP = "192.168.10.11"; // 本机IP
    public  int  LOCAL_PORT = 8888;   // 端口号
    public InetAddress inetAddress;
    public DatagramSocket msocketClient;   //
    public DatagramPacket Packet_Receive;  // 接受数据包

    // 构造方法
    public UdpClient(){
        try{
            inetAddress = InetAddress.getByName(SERVER_IP);
            msocketClient = new DatagramSocket();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    public interface  OnMsgReturnedListener{
        void onMsgReturned(String msg);
        void onError(Exception ex);
    }

    // 发送数据给服务端
    public void sendMsg (String msg, OnMsgReturnedListener listener){
        new Thread(){
            public void run(){
                super.run();
                try{
                    byte[] msgByte = msg.getBytes();
                    DatagramPacket clientPacket = new DatagramPacket(msgByte,
                            msgByte.length,
                            inetAddress,
                            LOCAL_PORT);
                    msocketClient.send(clientPacket);

                    byte[] buf = new byte[1024];
                    DatagramPacket serverMsgPacket = new DatagramPacket(buf,buf.length);
                    msocketClient.receive(serverMsgPacket);
                    String serverMsg = new String(serverMsgPacket.getData(),0,serverMsgPacket.getLength());

                    listener.onMsgReturned(serverMsg);
                }catch (Exception e){
                    listener.onError(e);
                }
            }
        }.start();
    }
    // 关闭套接字
    public void onDestory(){
        if(msocketClient != null){
            msocketClient.close();
        }
    }
}
